package com.example.springadminclient.healthIndicator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.Status;
import org.springframework.stereotype.Component;

import javax.swing.plaf.synth.SynthOptionPaneUI;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;

/**
 * 自定义健康指标
 */
@Component
public class HeapMemoryHealthIndicator implements HealthIndicator {

    private static final Logger log = LoggerFactory.getLogger(HeapMemoryHealthIndicator.class);

    private static final int WARNING_THRESHOLD_PERCENT = 80; // 警告阈值
    private static final int ERROR_THRESHOLD_PERCENT = 95; // 错误阈值

    private final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

    @Override
    public Health health() {
        MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        long used = heapMemoryUsage.getUsed();
        long max = heapMemoryUsage.getMax();
        double usagePercent = ((double) used / (double) max) * 100;
        if (usagePercent >= ERROR_THRESHOLD_PERCENT) {
            log.info("down:"+usagePercent);
            return Health.down().withDetail("Heap Usage", usagePercent).build();
        } else if (usagePercent >= WARNING_THRESHOLD_PERCENT) {
            log.info("unknown:"+usagePercent);
            //return Health.warn().withDetail("Heap Usage", usagePercent).build();
            return Health.down().withDetail("status","WARNING").withDetail("Heap Usage", usagePercent).build();
        }
        log.info("up:"+usagePercent);
        return Health.up().withDetail("Heap Usage", usagePercent).build();
    }
}